package io.plus.engine.utils.lock_capable_task;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Data
public class DefaultThreadFactory implements ThreadFactory {
    private static Map<String, DefaultThreadFactory> threadFactoryNameToThreadFactory = new HashMap<>();
    //
    private static Map<String, AtomicInteger> hreadFactoryNameToToAtomicIntegerMap = new HashMap<>();

    private String threadPoolName = null;
    private int priority = Thread.NORM_PRIORITY;

    private DefaultThreadFactory() {

    }

    //
    public static DefaultThreadFactory getInstance(String threadPoolName, Integer priority) {
        DefaultThreadFactory defaultThreadFactory = threadFactoryNameToThreadFactory.get(threadPoolName);
        if (defaultThreadFactory == null) {
            defaultThreadFactory = new DefaultThreadFactory();
            if (priority != null) {
                defaultThreadFactory.priority = priority;
            }
            defaultThreadFactory.setThreadPoolName(threadPoolName);
            threadFactoryNameToThreadFactory.put(threadPoolName, defaultThreadFactory);
            hreadFactoryNameToToAtomicIntegerMap.put(threadPoolName, new AtomicInteger());
        }
        return defaultThreadFactory;
    }

    @Override
    public Thread newThread(Runnable runnable) {
        Thread thread = new Thread(runnable);
        thread.setName(this.getThreadPoolName() + "-" + hreadFactoryNameToToAtomicIntegerMap.get(this.getThreadPoolName()).incrementAndGet());
        thread.setPriority(priority);
        return thread;
    }


}
